#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "err.hpp"

using namespace std;

class sock
{
    //listen第二个参数
    const static int backlog = 32;
public:
    //创建套接字
    static int Socket()
    {
        int listensock = socket(AF_INET,SOCK_STREAM,0);
        if(listensock < 0 )
        {
            //出错
            logMessage(ERROR,"create sock fail");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL,"create socket success");
        int opt = 1;
        setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,sizeof(opt));
        return listensock;
    }
    //绑定
    static void Bind(int sock,int port)
    {
        struct sockaddr_in local;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        int n = bind(sock,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            logMessage(ERROR,"bind fail");
            exit(BIND_ERR);
        }
        logMessage(NORMAL,"bind success");
    }
    //监听
    static void Listen(int listensock)
    {
        int n = listen(listensock,backlog);
        if(n < 0)
        {
            logMessage(ERROR,"listen fail");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL,"listen success");
    }
    //建立新连接
    static int Accept(int listensock,string* clientip,uint16_t* clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock = accept(listensock,(struct sockaddr*)&peer,&len);
        if(sock < 0)
        {
            logMessage(ERROR,"accept fail");
            exit(BIND_ERR);
        }
        else{
            logMessage(NORMAL,"accept success");
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }
        return sock;
    }
};